package hotnet.future;

import hotnet.session.IoSession;

public class DefaultConnectFuture extends DefaultIoFuture implements ConnectFuture {
	private static final Object CANCEL_OBJECT= new Object();
	
	public static ConnectFuture newFailedFuture(Throwable e) {
		DefaultConnectFuture connectFuture = new DefaultConnectFuture();
		connectFuture.setException(e);
		return connectFuture;
	}

	public DefaultConnectFuture() {
		super(null);
	}

	@Override
	public boolean isConnected() {
		return getValue() instanceof IoSession;
	}

	@Override
	public boolean isCanceled() {
		return getValue() == CANCEL_OBJECT;
	}

	@Override
	public void cancel() {
		setValue(CANCEL_OBJECT);
	}

	@Override
	public void completeConnect(IoSession session) {
		setValue(session);
	}
	
	@Override
	public IoSession getSession() {
        Object v = getValue();
        if (v instanceof RuntimeException) {
            throw (RuntimeException) v;
        } else if (v instanceof Error) {
            throw (Error) v;
        } else if (v instanceof Throwable) {
            throw (RuntimeException) new RuntimeException("Failed to get the session.").initCause((Throwable) v);
        } else if (v instanceof IoSession) {
            return (IoSession) v;
        } else {
            return null;
        }
	}
}
